﻿using AntdUI;
using Microsoft.VisualBasic.ApplicationServices;
using Super.Admin.Entities;
using Super.Admin.Global;
using Super.Admin.IServices;
using Super.Admin.Mappers;
using Super.Admin.Models.Department;
using Super.Admin.Models.Permission;
using Super.Admin.Models.Role;
using Super.Admin.Models.User;
using Super.Admin.Services;
using Super.Admin.Utils;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Views.Base;
using Super.Admin.Views.Main;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Super.Admin.Views.Page
{
    public partial class MenuManagementView : BaseUserControl
    {
        private readonly IPermissionService _permissionService;
        private readonly IUserOperateLogService _userOperateLogService;

        private List<PermissionBaseModel> _allPermissions = new ();
        private List<PermissionBaseModel> _menus = new ();

        private bool _isLoad = false;
        private List<CellButton> _cellButtons = new ();

        public MenuManagementView(IPermissionService permissionService, IUserOperateLogService userOperateLogService)
        {
            InitializeComponent();
            _permissionService = permissionService;
            _userOperateLogService = userOperateLogService;
            InitializeAuthPermissionList();
            this.Load += OnLoad; ;
        }

        private void OnLoad(object? sender, EventArgs e)
        {
            LoadPermissions();

            TablePermissionModel.Columns = new AntdUI.ColumnCollection
            {
                new AntdUI.Column("Id","ID",ColumnAlign.Center){ Width = "150",KeyTree = nameof(PermissionBaseModel.Children)},
                new AntdUI.Column("Name","名称",ColumnAlign.Center){ Width = "280"},
                new AntdUI.Column("TypeTag","类型",ColumnAlign.Center){ Width = "100"},
                new AntdUI.Column("IconText","图标",ColumnAlign.Center){ Width = "100"},
                new AntdUI.Column("Permissionkey","权限标识",ColumnAlign.Center){ Width = "300"},
                new AntdUI.Column("Path","路由路径",ColumnAlign.Center){ Width = "350"},
                new AntdUI.Column("IsActiveTag","状态",ColumnAlign.Center){ Width = "100"},
                new AntdUI.Column("Sort", "排序",ColumnAlign.Center) { Width = "80" },
                new AntdUI.Column("Operates","操作",ColumnAlign.Center){ColAlign = ColumnAlign.Center},
            };

        }

        private void InitializeAuthPermissionList()
        {
            BtnCreate.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.MenuCreate);

            // 单元格按钮
            _cellButtons.Clear();
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.MenuCreateChild))
                _cellButtons.Add(new CellButton(PermissionKeys.MenuCreateChild, "新增子菜单", TTypeMini.Primary));
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.MenuUpdate))
                _cellButtons.Add(new CellButton(PermissionKeys.MenuUpdate, "编辑", TTypeMini.Primary));
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.MenuDelete))
                _cellButtons.Add(new CellButton(PermissionKeys.MenuDelete, "删除", TTypeMini.Error));
       
        }

        public override void DoRefresh()
        {
            LoadPermissions();
        }

        private void LoadPermissions()
        {
            var menuEntities = _permissionService.GetPermissions().ToList();
            _allPermissions = menuEntities.ToBaseModels().ToList();
            foreach (var model in _allPermissions)
            {
                model.IconText = new CellImage(model.Icon);
                var operates = TableHelper.CopyCellButton(_cellButtons);
                if (model.Type == 2)
                    operates.RemoveAll(x => x.Id == PermissionKeys.MenuCreateChild);
                model.Operates = operates.ToArray();
            }
            _menus = BuildPermissionTree(_allPermissions, 0);
            TablePermissionModel.DataSource = _menus;
        }

        private List<PermissionBaseModel> BuildPermissionTree(List<PermissionBaseModel> source, int parentId = 0)
        {
            var children = source.Where(s => s.ParentId == parentId).ToList();
            foreach (var child in children)
            {
                child.PermissionChildren = BuildPermissionTree(source, child.Id);
                child.Children = child.PermissionChildren.ToArray();
            }
            return children;
        }

        private List<PermissionBaseModel> GetChildren(List<PermissionBaseModel> sourceModel, int parentId)
        {
            var children = sourceModel.Where(m => m.ParentId == parentId).ToList();
            foreach (var child in children)
            {
                child.Children = GetChildren(sourceModel, child.Id).ToArray();
                child.PermissionChildren = GetChildren(sourceModel, child.Id);
            }
            return new List<PermissionBaseModel>(children);
        }
        private void BtnCreate_Click(object sender, EventArgs e)
        {
            PermissionBaseModel model = new PermissionBaseModel();
            var modifyView = new MenuManagementModify(ParentForm, _menus, _allPermissions, model, "新增菜单");
            AntdUI.Modal.open(new Modal.Config(ParentForm, modifyView)
            {
                OnOk = ok =>
                {
                    if (!ValidateMenuModel(model, out string message))
                    {
                        AntdUI.Message.error(ParentForm, message);
                        return false;
                    }
                    _permissionService.CreatePermission(model.ToEntity());
                    AntdUI.Message.success(ParentForm, "添加成功");
                    DoRefresh();
                    return true;
                }
            });
        }

        private void TablePermissionModel_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is PermissionBaseModel model)
            {
                if (e.Btn.Id == PermissionKeys.MenuDelete)
                {
                    var result = AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "是否删除", new AntdUI.Modal.TextLine[]
                    {
                        new Modal.TextLine($"确认删除【[{model.Id}]{model.Name}】以及下面的子菜单吗",AntdUI.Style.Db.Primary),
                    }, AntdUI.TType.Error)
                    {
                        CancelText = "取消",
                        OkType = TTypeMini.Error,
                        OkText = "删除"
                    });
                    if (result == DialogResult.OK)
                    {
                        _permissionService.DeletePermission(model.Id);
                        _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"菜单管理删除：【[{model.Id}]{model.Name}】", "system:menu:delete");
                        AntdUI.Message.success(ParentForm, "删除成功");
                        DoRefresh();
                    }
                }
                else if (e.Btn.Id == PermissionKeys.MenuUpdate)
                {
                    // 为了防止同一个地址
                    PermissionBaseModel baseModel = model.ToEntity().ToBaseModel();
                    var modifyView = new MenuManagementModify(ParentForm, _menus, _allPermissions, baseModel, "编辑菜单");
                    AntdUI.Modal.open(new Modal.Config(ParentForm, modifyView)
                    {
                        OnOk = ok =>
                        {
                            if (!ValidateMenuModel(baseModel, out string message))
                            {
                                AntdUI.Message.error(ParentForm, message);
                                return false;
                            }
                            var baseParentModel = _allPermissions.FirstOrDefault(a => a.Id == model.ParentId);
                            _permissionService.UpdatePermission(baseModel.ToEntity());
                            AntdUI.Message.success(ParentForm, "修改成功");
                            DoRefresh();
                            return true;
                        }
                    });
                }
                else if (e.Btn.Id == PermissionKeys.MenuCreateChild)
                {
                    PermissionBaseModel baseModel = new PermissionBaseModel { ParentId = model.Id, PermissionParent = model };
                    var modifyView = new MenuManagementModify(ParentForm, _menus, _allPermissions, baseModel, "新增子菜单");
                    AntdUI.Modal.open(new Modal.Config(ParentForm, modifyView)
                    {
                        OnOk = ok =>
                        {
                            if (!ValidateMenuModel(baseModel, out string message))
                            {
                                AntdUI.Message.error(ParentForm, message);
                                return false;
                            }
                            _permissionService.CreatePermission(baseModel.ToEntity());
                            AntdUI.Message.success(ParentForm, "新增子菜单成功");
                            DoRefresh();
                            return true;
                        }
                    });
                }
            }
        }

        private bool ValidateMenuModel(PermissionBaseModel model, out string message)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                message = "名称不能为空";
                return false;
            }
            if (!ValidateParentType(model, out message))
            {
                return false;
            }
            message = string.Empty;
            return true;
        }
        
        private bool ValidateParentType(PermissionBaseModel model, out string message)
        {
            message = string.Empty;
            var parent = _allPermissions.FirstOrDefault(a => a.Id == model.ParentId);
            if (model.Type is 0 or 1)
            {
                if (parent != null && parent.Type != 0)
                {
                    message = "菜单/目录的父级只能是目录";
                    return false;
                }
            }
            else if (model.Type == 2)
            {
                if (parent == null || parent.Type != 1)
                {
                    message = "按钮的父级只能是菜单";
                    return false;
                }
            }
            return true;
        }
    }
}
